import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "loginFilter", urlPatterns = {"/login"})
public class loginFilter extends HttpFilter {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
	// 每次执行都新建一个连接
	String URL = getServletContext().getInitParameter("db.url");
	String NAME = getServletContext().getInitParameter("db.user");
	String PASSWORD = getServletContext().getInitParameter("db.password");

	UserBean userBean = new UserBean( URL, NAME, PASSWORD, req.getParameter("username"), req.getParameter("passwd"));

	try {
	    if(userBean.checkpass()==false) {
		HttpSession session = req.getSession(true);
		session.setAttribute("error", "login");
		//fallback to index.jsp when login fail 
		req.getRequestDispatcher("index.jsp").forward(req, res);
	    }
	    System.out.println("inside login filter");
	} catch (ServletException e) {
	    e.printStackTrace();
	}
	    System.out.println("inside login filter");
	    chain.doFilter(req,res);
    }

}
